﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Antlr.StringTemplate;

namespace MvcDemo.CustomViewEngines
{
    public class StringTemplateView : IView
    {
        #region 属性 Properties
        /// <summary>
        /// StringTemplate 对象, 在构造函数中创建
        /// </summary>
        private StringTemplate StringTemplate
        {
            get;
            set;
        }
        #endregion

        #region 构造函数 Constructed Function
        private StringTemplateView()
        {
            //不用于使用不带参数的构造函数
            this.StringTemplate = new StringTemplate();
        }
        public StringTemplateView(StringTemplate template)
        {
            //null check
            if (template == null) throw new ArgumentNullException("template");
            //set template
            this.StringTemplate = template;
        }
        #endregion

        #region IView 成员
        void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            foreach (var item in viewContext.ViewData)
            {
                this.StringTemplate.SetAttribute(item.Key.ToString(), item.Value.ToString());
            }
            //为StringTemplate设置HttpContext
            this.StringTemplate.SetAttribute("context", viewContext.HttpContext);
            //输出模板
            NoIndentWriter noIndentWriter = new NoIndentWriter(writer);
            this.StringTemplate.Write(noIndentWriter);
        }
        #endregion

        void IView.Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            throw new NotImplementedException();
        }
    }
}